/**
 * 
 */
package hu.myai.util;

import hu.myai.model.misc.KeyValue;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @author bozbalint
 * 
 */
public class Util {

	public Date addDays(Date date, int days) {

		GregorianCalendar initdate = new GregorianCalendar();

		initdate.setTime(date);
		initdate.add(Calendar.DATE, days);

		return initdate.getTime();
	}

	public KeyValue[] closestSupports(List<KeyValue[]> resultList) {

		KeyValue support = new KeyValue(false, null, Double.MIN_VALUE, null);
		KeyValue resistance = new KeyValue(false, null, Double.MAX_VALUE, null);

		for (KeyValue[] keyValues : resultList) {

			if (keyValues != null) {
				if (keyValues[0] != null && keyValues[0].getValue() > support.getValue()) {
					support = keyValues[0];
				}
				if (keyValues[1] != null && keyValues[1].getValue() < resistance.getValue()) {
					resistance = keyValues[1];
				}
			}
		}

		KeyValue[] retValue = { support, resistance };
		return retValue;
	}

	public String trim(Double number) {

		try {
			BigDecimal bigDecimal = new BigDecimal(number).setScale(3, BigDecimal.ROUND_FLOOR);
			return bigDecimal.toPlainString();
		} catch (NumberFormatException ex) {
			return "     ";
		}
	}

	public StringBuffer createIndexHtml(List<String> stringList) {
		StringBuffer sb = new StringBuffer("" + "<html>\n" + "<script language=javascript type='text/javascript'>\n"
				+ "function hidediv(value) {\n" + "     if (document.getElementById) { // DOM3 = IE5, NS6 \n"
				+ "        document.getElementById(value).src = \"http://www.foltzmartin.com/images/blank.gif\";\n"
				+ "        document.getElementById(value).style.visibility = 'hidden';\n" + "     }\n" + "}\n"
				+ "</script>\n" + "<body>\n");
		for (String symbol : stringList) {
			sb
					.append("<img ID=\""
							+ symbol
							+ "\" src=\"http://bigcharts.marketwatch.com/charts/big.chart?symb=AU:"
							+ symbol
							+ "&ma=4&maval=9&uf=0&lf=268435456&lf2=128&lf3=256&type=4&size=2&style=320&time=5&freq=1&nosettings=1&mocktick=1\" onclick=\"javascript:hidediv('"
							+ symbol + "')\"/><br/>\n");
		}
		sb.append("</body></html>");

		return sb;
	}

	public void writeIndexHtml(String data) {
		try {
			// Create file
			FileWriter fstream = new FileWriter("index.html");
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(data);
			// Close the output stream
			out.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}

}
